/*
 * Copyright (c) 2011 Anthony Vandikas
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation 
 * files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, 
 * modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 
 * is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE 
 * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "stdafx.h"
#include "PrintWidget.h"

#include "AbstractHistory.h"

PrintWidget::PrintWidget(AbstractHistory &history)
	: history(&history)
{
	ui.setupUi(this);

	connect(&history, SIGNAL(modified()), this, SLOT(updateLog()));
	updateLog();
}

void PrintWidget::printLog()
{
	QPrinter printer;
	QPrintDialog dialog(&printer, this);

	if (dialog.exec() != QPrintDialog::Accepted)
		return;

	ui.previewText->print(&printer);
}

void PrintWidget::updateLog()
{
	ui.previewText->setHtml(createHtml());
}

QString PrintWidget::createHtml()
{
	return QString("<html>%1%2</html>").
		arg(createHeader()).
		arg(createTable());
}

QString PrintWidget::createHeader()
{
	auto date = QDate::currentDate();

	return QString("<h1>Summary for %1</h1><hr>").
		arg(date.toString());
}

QString PrintWidget::createTable()
{
	return QString("<table border=1 cellspacing=0 cellpadding=3 width=100%>%1%2</table>").
		arg(createTableHeader()).
		arg(createTableRows());
}

QString PrintWidget::createTableHeader()
{
	return QString("<tr><th>%1</th><th>%2</th><th>%3</th></tr>").
		arg("Time").
		arg("Student").
		arg("Item");
}

QString PrintWidget::createTableRows()
{
	auto entries = history->filter(QDate::currentDate(), QDate::currentDate(), QStringList(), QStringList());

	QString output;
	foreach (auto entry, entries)
		output += createTableRow(entry);

	return output;
}

QString PrintWidget::createTableRow(const Entry &entry)
{
	return QString("<tr><td>%1</td><td>%2</td><td>%3</td></tr>").
		arg(entry.getTime().toString("hh:mm:ss ap")).
		arg(entry.getStudent().toString()).
		arg(entry.getItem().toString());
}
